/*
 * Created on 2005-2-22
 *
 */
package bma.common.langutil.convert.common;

import java.util.Date;

import bma.common.langutil.convert.Converter;
import bma.common.langutil.core.ClassUtil;
import bma.common.langutil.core.DateTimeUtil;
import bma.common.langutil.core.DateTimeValue;
import bma.common.langutil.core.DateValue;
import bma.common.langutil.core.ExceptionUtil;
import bma.common.langutil.core.ValueUtil;

/**
 * 常用对象的转换器<br/>
 * boolean/byte/char/int/long/string/class/enum/date/datetime
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 */
public class CommonConverter implements Converter {

	private static CommonConverter instance = new CommonConverter();

	public static CommonConverter getInstance() {
		return instance;
	}

	@Override
	public boolean canConvert(Class from, Class to) {
		return doCanConvert(from, to);
	}

	public static boolean doCanConvert(Class from, Class to) {

		if (ClassUtil.isMainClass(from) && ClassUtil.isMainClass(to)) {
			return true;
		}

		if (from == String.class) {
			if (to == Class.class) {
				return true;
			}
			if (to == DateValue.class) {
				return true;
			}
			if (to == DateTimeValue.class) {
				return true;
			}
		}

		if (to == String.class) {
			if (from == Class.class) {
				return true;
			}
			if (from == DateValue.class) {
				return true;
			}
			if (from == DateTimeValue.class) {
				return true;
			}
		}

		return false;
	}

	@Override
	public Object convertTo(Object src, Class to) {
		return doConvertTo(src, to);
	}

	public static Object doConvertTo(Object src, Class to) {
		if (src == null)
			return null;

		if (ValueUtil.isValueClass(to)) {
			try {
				return ValueUtil.toValue(to, src);
			} catch (Exception e) {
				throw ExceptionUtil.throwRuntime(e);
			}
		}

		if (to == String.class) {
			if (src instanceof Class) {
				return ((Class) src).getName();
			}
			if (src instanceof Date) {
				return DateTimeUtil.formatDateTime((Date) src);
			}
			if (src instanceof DateValue) {
				return DateTimeUtil.formatDate((DateValue) src);
			}
			if (to == DateTimeValue.class) {
				return DateTimeUtil.formatDateTime((DateTimeValue) src);
			}
		}
		if (src instanceof String) {
			if (to == Date.class) {
				return DateTimeUtil.parseDate((String) src, null);
			}
			if (to == DateValue.class) {
				Date dt = DateTimeUtil.parseDate((String) src, null);
				if (dt != null) {
					return new DateValue(dt.getTime());
				}
				return null;
			}
			if (to == DateTimeValue.class) {
				Date dt = DateTimeUtil.parseDateTime((String) src, null);
				if (dt != null) {
					return new DateTimeValue(dt.getTime());
				}
				return null;
			}
		}

		return null;
	}

}